package com.hmjk.health.health;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.BP_Evaluator;
import com.hmjk.health.util.BloodPressureData;
import com.hmjk.health.util.BloodPressureData.BP_DETAIL;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.GlycoseData;
import com.hmjk.health.util.GlycoseData.GLY_DETAIL;
import com.hmjk.health.util.GlycoseReferenceSet;
import com.hmjk.health.util.MULTI_USER_DEV_DATA;
import com.hmjk.health.util.HEALTH_KEY;
import com.hmjk.health.views.GlucBarView;
import com.hmjk.health.views.RefreshLayout;
import com.hmjk.health.views.RoundImageView;
import com.hmjk.health.views.RefreshLayout.OnRefreshListener;

public class HealthCardFragment extends Fragment implements OnClickListener{
	private final String TAG = HealthCardFragment.class.getSimpleName();

  public static final String BUNDLE_PARAM_SUB_TAB_ITEMS = "com.hmjk.health.healthcardsubtab";
  public static final String BUNDLE_PARAM_USER_INFO = "com.hmjk.health.accountinfo";
	
	
	private HealthApp mApp = null;
	private LayoutInflater mInflater;
	private boolean attached = false;
	private int mTotal = 0;
	
	private RefreshLayout refresh;
	private MULTI_USER_DEV_DATA mUserAccount;
	private String refreshing = null;
	
	private RoundImageView mPhoto;
	private TextView mName;
	private TextView mAge;
	private TextView mHeight;
	private TextView mWeight;
	private TextView mBMI;
	private ImageView mBMIIcon;
	private TextView mPageIndex;
	private TextView mDate;
	private LinearLayout mDataRoom;
	private View mWaitView;
	private View mGlucoseView;
	private View mBpView;
	//private View mSleepView;
	private View mTemperView;
	//private View mWeightView;
	
	private int queryHealthBGstatus = 0; //0 not query, 1 querying 2 finish
	private int queryHealthBPstatus = 0; //0 not query, 1 querying 2 finish
	private int queryHealthSetstatus = 0; //0 not query, 1 querying 2 finish
	private int queryPowerstatus = 0; //0 not query, 1 querying 2 finish
	
	private final long SEC_TIME_ONE_DAY = (long)(24 * 60 * 60 * 1000);
	
	private GlycoseReferenceSet set = null;
	private GlycoseData glyData = null;
	private BloodPressureData bpData = null;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	public HealthCardFragment(HealthApp app){
		super();
		mApp = app;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		Bundle args = getArguments();
		mInflater = inflater;
		
		mUserAccount =  (MULTI_USER_DEV_DATA) args.getSerializable("account");
		mTotal = args.getInt("total");
		
		View v = inflater.inflate(R.layout.health_card_item, container, false);
		
		//user's base date :photo name age height weight BMI
		mPhoto = (RoundImageView) v.findViewById(R.id.photo);
		mName = (TextView) v.findViewById(R.id.user_name);
		mAge = (TextView)v.findViewById(R.id.user_age);
		mHeight = (TextView) v.findViewById(R.id.height);
		mWeight = (TextView) v.findViewById(R.id.weight);
		mBMI = (TextView) v.findViewById(R.id.BMI);
		mBMIIcon = (ImageView) v.findViewById(R.id.bmi_icon);
		mPageIndex = (TextView) v.findViewById(R.id.pageIndex);
		mDate = (TextView) v.findViewById(R.id.date);
		mDataRoom = (LinearLayout) v.findViewById(R.id.outline_room);
		mGlucoseView = mInflater.inflate(R.layout.health_glucose_outline, null);
		mBpView = mInflater.inflate(R.layout.health_bp_outline, null);
		//mSleepView = mInflater.inflate(R.layout.health_sleep_outline, null);
		mTemperView = mInflater.inflate(R.layout.health_temperature_outline, null);
		//mWeightView = mInflater.inflate(R.layout.health_weight_outline, null);
		mWaitView = v.findViewById(R.id.data_waiting);
		
		if(mTotal == 1){
			mPageIndex.setVisibility(View.GONE);
		}else{
			mPageIndex.setVisibility(View.VISIBLE);
			mPageIndex.setText(""+(mUserAccount.index+1)+"/"+mTotal);
		}
		
		refresh = (RefreshLayout)v.findViewById(R.id.refresh_root);
		refresh.initScroll();
		refreshing = null;
		refresh.setOnRefreshListener(new OnRefreshListener(){

			@Override
			public void onRefresh() {
				refreshing = null;
				((HealthCardsActivity)getActivity()).refreshList(); //check from network per 2 minutes
				
				if(mUserAccount != null){
					String[] args = new String[]{mUserAccount.id, mUserAccount.subcode};
					boolean ok = mApp.getDataManager().refreshData(DataManager.F_DEVICESUBINFO, args);
					if(ok){
						if(refreshing == null){
							refreshing = new String(DataManager.F_DEVICESUBINFO);
						}else {
							refreshing += ":" + DataManager.F_DEVICESUBINFO;
						}
					}	
					
					queryHealthDataAndPower(mUserAccount.id, mUserAccount.subcode, true);
				}
				
				if(refreshing == null){
					Message m = mhandler.obtainMessage(MSG_CLOSE_REFRESH_VIEW);
					mhandler.sendMessageDelayed(m, 500);
				}
			}
			
		});
		
		//retrieveHealthData();
		mGlucoseView.setOnClickListener(this);
		mBpView.setOnClickListener(this);
		//mSleepView.setOnClickListener(this);
		mTemperView.setOnClickListener(this);
		//mWeightView.setOnClickListener(this);
		
		mDataRoom.addView(mGlucoseView);
		mDataRoom.addView(mBpView);
		//mDataRoom.addView(mSleepView);
		mDataRoom.addView(mTemperView);
		//mDataRoom.addView(mWeightView);
		
		return v;
	}
	
	public void updateArgs(Bundle args){
		mUserAccount = (MULTI_USER_DEV_DATA) args.getSerializable("account");
		mTotal = args.getInt("total");
		
		if(!attached)
			return;
		
		if(mPageIndex == null)
			return;
		
		if(mTotal == 1){
			mPageIndex.setVisibility(View.GONE);
		}else{
			mPageIndex.setVisibility(View.VISIBLE);
			mPageIndex.setText(""+(mUserAccount.index+1)+"/"+mTotal);
		}
		
		if(!refresh.isRefreshing()){
			updateUserBaseView();
			updateDataRoomView();
		}
	}
	
	private void updateHealthSet(){
		if(mUserAccount == null){
			return;
		}
		
		logd("updateHealthSet subcode=" + mUserAccount.subcode);
		updateGlucoseSet();
	}
	
	private void updateGlucoseSet(){
		String[] arg = new String[]{mUserAccount.id};
		set = (GlycoseReferenceSet) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_SET, arg);
		
	}
	
	private void updateHealthData(){
		if(mUserAccount == null){
			return;
		}
		
		logd("updateHealthData");
		updateGlucoseData();
		updateBpData();
		
	}
	
	private long getTimeInMillis(int year, int month, int day){
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month);
		c.set(Calendar.DATE, day);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		
		return c.getTimeInMillis();
	}
	
	//private boolean glucDataNull = true;
	private long lastTime;
	private float glucLastBgValue;
	private int glucLastBgType, glucCntToday, glucCntWeek;
	private int glucWeekGreat, glucWeekGood, glucWeekBad;
	
	private void updateGlucoseData(){
		Calendar c = Calendar.getInstance();
		long timeNow = c.getTimeInMillis();
		long timeFrom = getTimeInMillis(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)) - 6 * SEC_TIME_ONE_DAY;
		String[] argStrings = new String[]{mUserAccount.id, mUserAccount.subcode, String.valueOf(timeFrom), String.valueOf(timeNow)};
		glyData = (GlycoseData) mApp.getDataManager().checkData(DataManager.F_GLYCOSE_DATA, argStrings);

	}
	
	private void updateBpData(){
		Calendar c = Calendar.getInstance();
		long timeNow = c.getTimeInMillis();
		long timeFrom = getTimeInMillis(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)) - 6 * SEC_TIME_ONE_DAY;
		String[] argStrings = new String[]{mUserAccount.id, mUserAccount.subcode, String.valueOf(timeFrom), String.valueOf(timeNow)};
		bpData = (BloodPressureData) mApp.getDataManager().checkData(DataManager.F_BP_DATA, argStrings);
	}
	
	private void queryHealthDataDone(String tag, boolean updated){
		if(DataManager.F_GLYCOSE_DATA.equals(tag)){
			queryHealthBGstatus = 2;
		}else if(DataManager.F_GLYCOSE_SET.equals(tag)){
			queryHealthSetstatus = 2;
		}else if(DataManager.F_BP_DATA.equals(tag)){
			queryHealthBPstatus = 2;
		}
		
		if((queryHealthBGstatus == 2) && (queryHealthSetstatus == 2) && (queryHealthBPstatus == 2)){
			if(updated){
				updateHealthData();
				updateHealthSet();
			}
			
			Message m = mhandler.obtainMessage(MSG_UPDATE_AFTER_QURREY);
			mhandler.sendMessageDelayed(m, 800);
			
		}
	}
	
	public void queryHealthDataAndPower(String tid, String subcode, boolean force){
		logd("queryLocationAndPower tid=" + tid + " subcode= "+subcode);
		logd("queryLocationAndPower queryHealthBGstatus=" + queryHealthBGstatus + " force= "+force);
		boolean update = false;
		if((queryHealthBGstatus == 0) || force){
			HEALTH_KEY key = new HEALTH_KEY(tid, subcode);
			boolean ok = mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_DATA, key);
			
			if(ok){
				logd("queryHealthData querying");
				queryHealthBGstatus = 1;
				update = true;
			}else{
				logd("queryHealthData no need");
				queryHealthBGstatus = 2;
			}
		}
		
		logd("queryLocationAndPower queryHealthSetstatus=" + queryHealthSetstatus + " force= "+force);
		if((queryHealthSetstatus == 0) || force){
			String[] args = new String[]{tid};
			boolean ok = mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_SET, args);
			
			if(ok ){
				logd("queryHealthSet querying");
				queryHealthSetstatus = 1;
				update = true;
			}else{
				logd("queryHealthSey no need");
				queryHealthSetstatus = 2;
			}
		}
		
		logd("queryLocationAndPower queryHealthBPstatus=" + queryHealthBPstatus + " force= "+force);
		if((queryHealthBPstatus == 0) || force){
			HEALTH_KEY key = new HEALTH_KEY(tid, subcode);
			boolean ok = mApp.getDataManager().refreshData(DataManager.F_BP_DATA, key);
			
			if(ok){
				logd("queryHealthBPData querying");
				queryHealthBPstatus = 1;
				update = true;
			}else{
				logd("queryHealthBPData no need");
				queryHealthBPstatus = 2;
			}
		}
		
		if(update)
			updateDataRoomView();
		
		logd("queryLocationAndPower queryPowerstatus=" + queryPowerstatus + " force= "+force);
		if((queryPowerstatus == 0) || force){
			//boolean update = false;
			boolean ok = mApp.getDataManager().refreshData(DataManager.F_DEVICE_POWER, tid);
			if(ok){
				logd("queryPower querying");
				queryPowerstatus = 1;
				//update = true;
			}else{
				logd("queryPower no need");
				//if(querystatus != 2)
				//	update = true;
				queryPowerstatus = 2;
			}
		}
	}
	
	private final int MSG_CLOSE_REFRESH_VIEW = 411;
	private final int MSG_UPDATE_AFTER_QURREY = 412;
	private Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_CLOSE_REFRESH_VIEW:{
				cancelRefresh();
			}
			break;
			case MSG_UPDATE_AFTER_QURREY:{
				updateDataRoomView();
			}break;
			}
		}
	};
	
	private void updateDataRoomView(){
		logd("updateDataRoomView");
		if(attached == false){
			logd("updateGlucoseItemView not attached");
			return;
		}
		
		if((queryHealthBGstatus == 1) || (queryHealthSetstatus == 1) || (queryHealthBPstatus == 1)){
			mWaitView.setVisibility(View.VISIBLE);
			return;
		}else{
			mWaitView.setVisibility(View.GONE);
		}
		
		updateGlucoseItemView();
		updateBpItemView();

	}
	
	private void updateGlucoseItemView(){
		if(attached == false){
			logd("updateGlucoseItemView not attached");
			return;
		}
		
		if(set == null){
			logd("updateGlucoseItemView glucose set is null");
			return;
		}
		
		if(glyData == null){
			logd("updateGlucoseItemView glucose data is null");
			return;
		}
		/*
		if(glyData.getAddrList().isEmpty()){
			
			return;
		}*/
		
		int cntToday = 0, cntWeek = 0;
		Calendar c = Calendar.getInstance();
		long timeToday0 = getTimeInMillis(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
		glucWeekGreat = 0;
		glucWeekGood = 0;
		glucWeekBad = 0;
		GLY_DETAIL lastGly = null;
		if(glyData.getAddrList().isEmpty() == false){
			lastGly = glyData.getAddrList().get(glyData.getListSize() - 1);
		}
		for(GLY_DETAIL d:glyData.getAddrList()){
			if(((d.recordTime - timeToday0) < SEC_TIME_ONE_DAY) && (d.recordTime >= timeToday0)){
				cntToday ++;
			}
			if((timeToday0 - d.recordTime) <= 6 * SEC_TIME_ONE_DAY){
				cntWeek ++;
				float upper = d.bgvalue * 115 / 100;
				float lower = d.bgvalue * 85 / 100;
				if(d.bgtype == 1){
					if((upper <= set.dawnupper) && (lower >= set.dawnlow)){
						glucWeekGreat ++;
					}else if((upper < set.dawnlow) || (lower > set.dawnupper)){
						glucWeekBad ++;
					}else {
						glucWeekGood ++;
					}
				}else if((d.bgtype == 2) || (d.bgtype == 4) || (d.bgtype == 6)){
					if((upper <= set.beforeupper) && (lower >= set.beforelow)){
						glucWeekGreat ++;
					}else if((upper < set.beforelow) || (lower > set.beforeupper)){
						glucWeekBad ++;
					}else {
						glucWeekGood ++;
					}
				}else if((d.bgtype == 3) || (d.bgtype == 5) || (d.bgtype == 7)){
					if((upper <= set.afterupper) && (lower >= set.afterlow)){
						glucWeekGreat ++;
					}else if((upper < set.afterlow) || (lower > set.afterupper)){
						glucWeekBad ++;
					}else {
						glucWeekGood ++;
					}
				}else {
					if((upper <= set.bedtimeupper) && (lower >= set.bedtimelow)){
						glucWeekGreat ++;
					}else if((upper < set.bedtimelow) || (lower > set.bedtimeupper)){
						glucWeekBad ++;
					}else {
						glucWeekGood ++;
					}
				}
				
			}

		}
		
		if(lastGly != null){
			lastTime = lastGly.recordTime;
			glucLastBgValue = lastGly.bgvalue;
			glucLastBgType = lastGly.bgtype;
		}
		glucCntToday = cntToday;
		glucCntWeek = cntWeek;
		
		TextView mGlucValueDate = (TextView)mGlucoseView.findViewById(R.id.gluc_value_date);
		String tmpString = getResources().getString(R.string.gluc_ctl_before_dawn);
		if((glucLastBgType == 2) || (glucLastBgType == 4) || (glucLastBgType == 6)){
			tmpString = getResources().getString(R.string.gluc_ctl_before_meal);
		}else if((glucLastBgType == 3) || (glucLastBgType == 5) || (glucLastBgType == 7)){
			tmpString = getResources().getString(R.string.gluc_ctl_after_meal);
		}else if(glucLastBgType == 8){
			tmpString = getResources().getString(R.string.gluc_ctl_before_sleep);
		}
		if(lastTime == 0){
			mGlucValueDate.setText(getResources().getString(R.string.measure_null_value));
		}else {
			String sglucvalue = null;
			if((set != null) && (set.unit == 0)){// mg/dL
				int mgdl = (int) (glucLastBgValue * 18);
				sglucvalue = String.valueOf(mgdl);
			}else{
				sglucvalue = String.valueOf(glucLastBgValue);
			}
			mGlucValueDate.setText(sglucvalue + " " + tmpString);
		}
		
		Time t = new Time();
		t.set(lastTime);
		if((lastTime  >=  timeToday0) && (lastTime < (timeToday0 + SEC_TIME_ONE_DAY))){
			tmpString = getResources().getString(R.string.measure_today);
		}else if((lastTime  <  timeToday0) && (lastTime > (timeToday0 - SEC_TIME_ONE_DAY))){
			tmpString = getResources().getString(R.string.measure_yestoday);
		}else {
			tmpString = String.valueOf(t.year) + "-" + String.valueOf(t.month + 1) + "-" + String.valueOf(t.monthDay);
		}
		TextView mLastTime = (TextView)mGlucoseView.findViewById(R.id.last_time);
		String hour = String.valueOf(t.hour);
		if(hour.length() == 1){
			hour = "0" + hour;
		}
		String minute = String.valueOf(t.minute);
		if(minute.length() == 1){
			minute = "0" + minute;
		}
		if(lastTime == 0){
			mLastTime.setText(getResources().getString(R.string.measure_null_value));
		}else {
			mLastTime.setText(tmpString + " " + hour + ":" + minute);
		}
		
		TextView mCntToday = (TextView)mGlucoseView.findViewById(R.id.gluc_times);
		tmpString = String.valueOf(glucCntToday) + " " + getResources().getString(R.string.measure_times_unit);
		mCntToday.setText(tmpString.trim());
		TextView mCntWeek = (TextView)mGlucoseView.findViewById(R.id.week_times);
		tmpString = String.valueOf(glucCntWeek) + " " + getResources().getString(R.string.measure_times_unit);
		mCntWeek.setText(tmpString.trim());
		TextView outlineHint = (TextView)mGlucoseView.findViewById(R.id.outline_hint);
		if(glucCntToday == 0){
			outlineHint.setVisibility(View.VISIBLE);
		}
		
		GlucBarView mGlucBar = (GlucBarView)mGlucoseView.findViewById(R.id.glucbar);
		mGlucBar.setGlucValues(glucWeekGreat, glucWeekGood, glucWeekBad);
		logd("mGlucBar.setGlucValues, glucWeekGreat=" + glucWeekGreat + ", glucWeekGood=" + glucWeekGood + ", glucWeekBad=" + glucWeekBad);
		
	}
	
	private void updateBpItemView(){
		if(attached == false){
			logd("updateBpItemView not attached");
			return;
		}
		
		if(bpData == null){
			logd("updateBpItemView bp data is null");
			return;
		}
		
		logd("updateBpItemView bpData:" + bpData);
		
		Calendar c = Calendar.getInstance();
		long timeToday0 = getTimeInMillis(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
		
		BP_DETAIL bp = bpData.getLatestBpvalue();
		if(bp != null){
			logd("updateBpItemView bp:" + bp);
			TextView mSbp = (TextView)mBpView.findViewById(R.id.sbp);
			mSbp.setText(String.valueOf(bp.sbp));
			ImageView mSbpHint = (ImageView)mBpView.findViewById(R.id.sbphint);
			int lvl = BP_Evaluator.checkSBP(bp.sbp);
			if(lvl == BP_Evaluator.LEV_LOW){
				mSbpHint.setVisibility(View.VISIBLE);
				mSbpHint.setImageResource(R.drawable.health_toolow);
			}else if(lvl == BP_Evaluator.LEV_HIGH){
				mSbpHint.setVisibility(View.VISIBLE);
				mSbpHint.setImageResource(R.drawable.health_toohigh);
			}else {
				mSbpHint.setVisibility(View.INVISIBLE);
			}
			
			TextView mDbp = (TextView)mBpView.findViewById(R.id.dbp);
			mDbp.setText(String.valueOf(bp.dbp));
			ImageView mDbpHint = (ImageView)mBpView.findViewById(R.id.dbphint);
			lvl = BP_Evaluator.checkDBP(bp.dbp);
			if(lvl == BP_Evaluator.LEV_LOW){
				mDbpHint.setVisibility(View.VISIBLE);
				mDbpHint.setImageResource(R.drawable.health_toolow);
			}else if(lvl == BP_Evaluator.LEV_HIGH){
				mDbpHint.setVisibility(View.VISIBLE);
				mDbpHint.setImageResource(R.drawable.health_toohigh);
			}else {
				mDbpHint.setVisibility(View.INVISIBLE);
			}
			
			TextView mPulse = (TextView)mBpView.findViewById(R.id.pulse_content);
			mPulse.setText(String.valueOf(bp.pulse));
			
			String tmpString = "";
			Time t = new Time();
			t.set(bp.recordtime);
			if((bp.recordtime  >=  timeToday0) && (bp.recordtime < (timeToday0 + SEC_TIME_ONE_DAY))){
				tmpString = getResources().getString(R.string.measure_today);
			}else if((bp.recordtime  <  timeToday0) && (bp.recordtime > (timeToday0 - SEC_TIME_ONE_DAY))){
				tmpString = getResources().getString(R.string.measure_yestoday);
			}else {
				tmpString = String.valueOf(t.year) + "-" + String.valueOf(t.month + 1) + "-" + String.valueOf(t.monthDay);
			}
			TextView mTime = (TextView)mBpView.findViewById(R.id.m_time_content);
			mTime.setText(tmpString);
		}
		
		int weekCnt = 0;
		int weekCntHigh = 0;
		int weekCntLow = 0;
		
		for(BP_DETAIL d:bpData.getDataList()){
			weekCnt ++;
			int lvlSbp = BP_Evaluator.checkSBP(d.sbp);
			int lvlDbp = BP_Evaluator.checkDBP(d.dbp);
			if((lvlSbp == BP_Evaluator.LEV_HIGH) || ((lvlDbp == BP_Evaluator.LEV_HIGH))){
				weekCntHigh ++;
			}else if(((lvlSbp == BP_Evaluator.LEV_LOW)) || ((lvlDbp == BP_Evaluator.LEV_LOW))){
				weekCntLow ++;
			}
		}
		
		TextView mWeekTimes = (TextView)mBpView.findViewById(R.id.weektimes);
		mWeekTimes.setText(String.valueOf(weekCnt) + " " + getResources().getString(R.string.measure_times_unit));
		TextView mWeekHighTimes = (TextView)mBpView.findViewById(R.id.higher);
		mWeekHighTimes.setText(getResources().getString(R.string.gluc_ctl_level_high, String.valueOf(weekCntHigh)) + " " + getResources().getString(R.string.measure_times_unit));
		TextView mWeekLowTimes = (TextView)mBpView.findViewById(R.id.lower);
		mWeekLowTimes.setText(getResources().getString(R.string.gluc_ctl_level_low, String.valueOf(weekCntLow)) + " " + getResources().getString(R.string.measure_times_unit));
		
	}
	
	/*
	private void showWaitingGlucoseItem(boolean show){
		ImageView mWaiting = (ImageView)mGlucoseView.findViewById(R.id.waiting);
		if(show){
			mWaiting.setVisibility(View.VISIBLE);
			Animation animWait = AnimationUtils.loadAnimation(getActivity(), R.anim.rotatecycled);
			mWaiting.startAnimation(animWait);
		}else {
			mWaiting.setVisibility(View.INVISIBLE);
		}
	}*/
	
	private int birthday2Age(String birthday){
		int pos = birthday.indexOf("-");
		String years = birthday.substring(0, pos);
		int yeari = Integer.parseInt(years);
		Time time = new Time();
		time.setToNow();
		int age = time.year - yeari;
		return age;
	}
	
	private int getIconByAgeAndGender(int age, String gender){
		//return R.drawable.default_photo;
		if(gender.equalsIgnoreCase("F")){
			if(age < 16){
				return R.drawable.health_account_girl;
			}else if(age > 60){
				return R.drawable.health_account_oldlady;
			}else {
				return R.drawable.health_account_lady;
			}
		}else {
			if(age < 16){
				return R.drawable.health_account_boy;
			}else if(age > 60){
				return R.drawable.health_account_oldman;
			}else {
				return R.drawable.health_account_man;
			}
		}
	}
	
	private void updateUserBaseView(){
		if(attached == false){
			return;
		}
		
		if((mUserAccount.nick != null) && (mUserAccount.nick.trim().length() > 0)){
			mName.setText(mUserAccount.nick);
		}else{
			String name = getResources().getString(R.string.noName);
			if((mUserAccount.name != null) && (mUserAccount.name.trim().length() > 0)){
				name = mUserAccount.name;
			}
			String subcode = String.valueOf(mUserAccount.subcode);
			if(subcode.length() < 2){
				subcode = "0"+subcode;
			}
			mName.setText(name+" "+subcode);
		}
		
		if(mUserAccount.birthday.trim().isEmpty() || mUserAccount.birthday.trim().startsWith("0000")){
			mAge.setText(getResources().getString(R.string.age, "--"));
			int icon = getIconByAgeAndGender(-1,mUserAccount.gender);
			mPhoto.setImageResource(icon);
		}else{
			int age = birthday2Age(mUserAccount.birthday);
			mAge.setText(getResources().getString(R.string.age, age));
			int icon = getIconByAgeAndGender(age,mUserAccount.gender);
			mPhoto.setImageResource(icon);
		}
		
		mPhoto.setType(RoundImageView.TYPE_RECT);
		mPhoto.setBackgroundResource(R.drawable.round_photo_bg);
		
		mHeight.setText(getResources().getString(R.string.health_height, 
				(mUserAccount.height > 0.0f)?String.valueOf(mUserAccount.height):"--"));
		
		mWeight.setText(getResources().getString(R.string.health_weight, 
				(mUserAccount.weight > 0.0f)?String.valueOf(mUserAccount.weight):"--"));
		
		if((mUserAccount.height > 0.0f) && (mUserAccount.weight > 0.0f)){
			double dbmi = mUserAccount.weight/(mUserAccount.height/100.0f)/(mUserAccount.height/100.0f);
			int ibmi = (int) (dbmi * 100);
			int fourth = ibmi%10;
			ibmi = (int) (dbmi * 10);
			if(fourth >= 5){
				ibmi += 1;
			}
			float fbmi = (ibmi*1.0f)/10.0f;
			String bmis = String.valueOf(fbmi);
			mBMI.setText(getResources().getString(R.string.BMI, bmis));
			if(fbmi > 24.0f){
				mBMIIcon.setVisibility(View.VISIBLE);
				mBMIIcon.setImageResource(R.drawable.health_toohigh);
			}else if(fbmi <= 18.5f){
				mBMIIcon.setVisibility(View.VISIBLE);
				mBMIIcon.setImageResource(R.drawable.health_toolow);
			}else{
				mBMIIcon.setVisibility(View.INVISIBLE);
			}
		}else{
			mBMI.setText(getResources().getString(R.string.BMI, "--"));
			mBMIIcon.setVisibility(View.INVISIBLE);
		}
		
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = df.format(calendar.getTime());
		mDate.setText(dateString);
	}
	
	public void focusChange(boolean focus){
		refreshing = null;
		if(refresh != null)
			refresh.stopRefreshing();
		if(focus && (mUserAccount != null)){
			queryHealthDataAndPower(mUserAccount.id, mUserAccount.subcode, false);
		}
		
	}
	
	public boolean cancelRefresh(){
		refreshing = null;
		if((refresh != null) && refresh.isRefreshing()){
			refresh.stopRefreshing();
			return true;
		}
		return false;
	}
	
	public boolean isRefreshing(){
		if(refresh != null)
			return refresh.isRefreshing();
		
		return false;
	}
	
	private void updateRefreshFlag(String clear){
		if(refreshing == null){
			logd("updateRefreshFlag, refreshing is null");
			return;
		}
		logd("updateRefreshFlag clear=" + clear);
		
		if(refreshing.contains(clear)){
			String[] ss = refreshing.split(":");
			String flag = "";
			for(String s:ss){
				if(s.equalsIgnoreCase(clear) == false){
					if(flag.equals("") == false){
						flag += ":";
					}
					flag += s;
				}
			}
			if(flag.trim().isEmpty())
				refreshing = null;
			else{
				refreshing = flag.trim();
			}
		}
	}
	
	private void updateSubAccoutData(){
		if(mUserAccount == null){
			return;
		}
		
		String[] arg1 = new String[2];
		arg1[0] = "DEV_TID";
		arg1[1] = mUserAccount.id;
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, arg1);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				if(ar.length() > 0){
					JSONObject e = ar.getJSONObject(0);
					mUserAccount.id = e.getString("tid");
					mUserAccount.name = e.getString("name");
						
					String ss = e.getString("status");
					mUserAccount.status = Integer.parseInt(ss);
						
					mUserAccount.type = e.getString("type");
						
					String a = e.getString("admin");
					mUserAccount.admin = Integer.parseInt(a);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		if(DEV_DATA.isHealthDev(mUserAccount.type) == false){
			mUserAccount = null;
			return;
		}
		
		String[] args = new String[3];
		args[0] = "TID_SUBCODE";
		args[1] = mUserAccount.id;
		args[2] = mUserAccount.subcode;
		JSONObject subinfo = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICESUBINFO,args);
		if(subinfo != null){
			try {
				JSONArray subar = subinfo.getJSONArray("array");
				int sublen = subar.length();
				if(sublen > 0){
					JSONObject subone = subar.getJSONObject(0);
					
					mUserAccount.nick = subone.getString("nickname");
					mUserAccount.birthday = subone.getString("birthday");
					mUserAccount.gender = subone.getString("gender");
					mUserAccount.height = subone.getDouble("height");
					mUserAccount.weight = subone.getDouble("weight");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public void refreshResult(String tag, boolean update){
		if(DataManager.F_DEVICESUBINFO.equals(tag)){
			if(refreshing != null){
				updateRefreshFlag(tag);
				if(refreshing == null){
					cancelRefresh();
					/*update all*/
					updateSubAccoutData();
					updateHealthData();
					updateHealthSet();
					updateUserBaseView();
					updateDataRoomView();
				}
			}else if(update){
				updateSubAccoutData();
				updateUserBaseView();
			}
		}else if(tag.equals(DataManager.F_GLYCOSE_DATA)){
			queryHealthDataDone(DataManager.F_GLYCOSE_DATA,update);
		}else if(tag.equals(DataManager.F_GLYCOSE_SET)){
			queryHealthDataDone(DataManager.F_GLYCOSE_SET,update);
		}else if(tag.equals(DataManager.F_BP_DATA)){
			queryHealthDataDone(DataManager.F_BP_DATA, update);
		}
	}
	
	/*
	private void queryRoomData(){
		queryRoomGlucData();
	}
	
	private void queryRoomGlucData(){
		GLY_KEY args = new GLY_KEY(mUserAccount.id, mUserAccount.subcode);
		mApp.getDataManager().refreshData(DataManager.F_GLYCOSE_DATA, args);
		//showWaitingCardRoom(true);
		
	}*/
	
	@Override
	public void onAttach(Activity a){
		logd("onAttach");
		super.onAttach(a);
		attached = true;
		//updateHealthSet();
		//updateHealthData();
	}
	
	@Override
	public void onDetach(){
		logd("onDetach");
		attached = false;
		super.onDetach();
	}
	
	@Override
	public void onResume(){
		logd("onResume");
		super.onResume();
		
		if(mUserAccount != null){
			logd("mUserAccount, id=" + mUserAccount.id + ", subcode=" + mUserAccount.subcode);
		}
		updateSubAccoutData();
		updateUserBaseView();
		
		updateHealthSet();
		updateHealthData();
		updateDataRoomView();
	}

	@Override
	public void onClick(View v) {
		if(mGlucoseView == v){
			Intent intent = new Intent();  
	        Bundle bundle = new Bundle();  
	        bundle.putSerializable(HealthCardFragment.BUNDLE_PARAM_SUB_TAB_ITEMS,"fragmentBloodSugar");  
	        bundle.putSerializable(HealthCardFragment.BUNDLE_PARAM_USER_INFO, mUserAccount);  
	        intent.setClass(getActivity(),HealthCardsOverViewActivity.class);  
	        intent.putExtras(bundle);  
	        startActivity(intent);  		
		}else if(mBpView == v){
			Intent intent = new Intent();  
            Bundle bundle = new Bundle();  
            bundle.putSerializable(HealthCardFragment.BUNDLE_PARAM_SUB_TAB_ITEMS,"fragmentBloodPressure");  
            bundle.putSerializable(HealthCardFragment.BUNDLE_PARAM_USER_INFO, mUserAccount);  
            intent.setClass(getActivity(),HealthCardsOverViewActivity.class);  
            intent.putExtras(bundle);  
            startActivity(intent);
		}/*else if(mSleepView == v){
			Intent i = new Intent(getActivity(), HealthCardsOverViewActivity.class);
			i.putExtra("page", "fragmentSleep");
			startActivity(i);
		}*/else if(mTemperView == v){
			Intent intent = new Intent();  
	        Bundle bundle = new Bundle();  
	        bundle.putSerializable(HealthCardFragment.BUNDLE_PARAM_SUB_TAB_ITEMS,"fragmentTemperature");  
	        bundle.putSerializable(HealthCardFragment.BUNDLE_PARAM_USER_INFO, mUserAccount);  
	        intent.setClass(getActivity(),HealthCardsOverViewActivity.class);  
	        intent.putExtras(bundle);  
	        startActivity(intent);			
		}/*else if(mWeightView == v){
			Intent i = new Intent(getActivity(), HealthCardsOverViewActivity.class);
			i.putExtra("page", "fragmentWeight");
			startActivity(i);
		}*/
	}
}
